//
//  View+Animat.swift
//  TTCOM
//
//  Created by Toj on 12/28/22.
//

import Foundation
import UIKit

private var runtime_flowLight_animation_key = "flowLight_animation_key"
private var runtime_flowLight_layer_key = "flowLight_layer_key"
public extension UIView {
    
    private var fl_isAnimation: Bool {
        get {
            let associatedValue = objc_getAssociatedObject(self, &runtime_flowLight_animation_key)
            return (associatedValue as? Bool) ?? false
        }
        set {
            objc_setAssociatedObject(self, &runtime_flowLight_animation_key, newValue, .OBJC_ASSOCIATION_ASSIGN)
        }
    }
    
    private var fl_layer: CAGradientLayer? {
        get {
            let associatedValue = objc_getAssociatedObject(self, &runtime_flowLight_layer_key)
            return associatedValue as? CAGradientLayer
        }
        set {
            objc_setAssociatedObject(self, &runtime_flowLight_layer_key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    func fl_startAnimation(color: UIColor, duration: TimeInterval, timeInterval: TimeInterval = 1, repeatCount: Float = MAXFLOAT, animationDelegate: CAAnimationDelegate? = nil) {
        guard !fl_isAnimation else { return }
        fl_isAnimation = true
        
        let gLayer = CAGradientLayer()
        
        let middleColor = color.tt_alpha(0.4).cgColor
        let fadeRef = color.tt_alpha(0).cgColor
        gLayer.colors = [fadeRef, middleColor, fadeRef]
        gLayer.locations = [0.6, 0.99, 0.99]
        
        gLayer.startPoint = CGPoint(x: 0, y: 0)
        gLayer.endPoint = CGPoint(x: 1, y: 0.06)
        
        var rect = bounds
       rect.size.width = bounds.width + 100
        gLayer.frame = rect;
        layer.addSublayer(gLayer)
        fl_layer = gLayer
   
        let startX = -gLayer.frame.size.width
        let endX = 100
        
        let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
        animation.delegate = animationDelegate
        let duration = duration > 0 ? duration : 1
        let interval = timeInterval > 0 ? timeInterval : 1
        
        let durationKeyTimes = duration / (duration + interval)
        animation.values = [startX, endX, endX]
        animation.duration = duration + interval
        animation.keyTimes = [0, NSNumber(value: durationKeyTimes), 1]
        animation.repeatCount = repeatCount
        animation.isRemovedOnCompletion = false

        // forwards: 像往常一样播放动画, 但将动画的最后一帧保留到屏幕上, 直到你移除动画.
        animation.fillMode = .forwards
        gLayer.add(animation, forKey: runtime_flowLight_layer_key)
    }
    
    func fl_stopAnimation() {
        fl_isAnimation = false

        fl_layer?.removeAnimation(forKey: runtime_flowLight_layer_key)
        fl_layer?.removeFromSuperlayer()
        fl_layer = nil
    }
}
